package com.h.forum.controller;

import com.h.forum.common.constant.Constants;
import com.h.forum.common.enums.ResultCode;
import com.h.forum.common.utils.JWTUtil;
import com.h.forum.pojo.model.Message;
import com.h.forum.pojo.request.MessageReplyRequest;
import com.h.forum.pojo.request.MessageSendRequest;
import com.h.forum.pojo.response.AppResult;
import com.h.forum.pojo.response.UserInfoResponse;
import com.h.forum.services.IMessageService;
import com.h.forum.services.IUserService;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource(name = "messageServiceImpl")
    private IMessageService messageService;

    @Resource(name = "userServiceImpl")
    private IUserService userService;

    /**
     * 发送站内信息
     * @param request
     * @return
     */
    @PostMapping("/send")
    public AppResult send(@Validated @RequestBody MessageSendRequest request) {
        // 查看当前用户的状态
        Long userId = JWTUtil.getUserIdFromToken(Constants.JWT);
        UserInfoResponse userInfo = userService.selectById(userId);
        if (userInfo.getState().equals(Constants.IS_STATUS_STATE)) {
            // 返回用户状态异常
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        // 检查是否是自己给自己发送信息
        if (request.getReceiverUserId().equals(userId)) {
            return AppResult.fail("不能给自己发送站内信");
        }

        // 检验接收者是否存在
        UserInfoResponse userInfoReceive = userService.selectById(request.getReceiverUserId());
        if (userInfoReceive == null) {
            // 返回接收者状态不正常
            return AppResult.fail("接收者状态异常");
        }

        // 封装对象
        Message message = new Message();
        message.setPostUserId(userId);
        message.setReceiveUserId(request.getReceiverUserId());
        message.setContent(request.getContent());

        // 调用Service层
        messageService.create(message);

        return AppResult.success();
    }

    /**
     * 返回未读数
     */
    @GetMapping("/getUnreadCount")
    public AppResult getUnreadCount() {
        Long userId = JWTUtil.getUserIdFromToken(Constants.JWT);

        // 调用Service层
        Integer count = messageService.selectUnreadCount(userId);

        return AppResult.success(count);
    }

    /**
     * 查询用户的所有站内信
     * @return 站内信集合
     */
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll () {
        // 1. 获取当前登录的用户
        Long userId = JWTUtil.getUserIdFromToken(Constants.JWT);
        // 2. 调用Service
        List<Message> messages = messageService.selectByReceiveUserId(userId);
        // 3. 返回结果
        return AppResult.success(messages);
    }

    /**
     * 更新站内信的状态
     * @param id
     * @return
     */
    @PostMapping("/markRead")
    public AppResult markRead(@RequestParam(value = "id") @NotNull Long id) {
        // 根据Id查询对应的站内信的状态
        Message message = messageService.selectById(id);
        if (message == null
                || message.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            // 返回错误信息
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 3. 站内信是不是自己的
        Long userId = JWTUtil.getUserIdFromToken(Constants.JWT);
        if (userId != message.getReceiveUserId()) {
            // 返回错误信息
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        // 调用Service
        messageService.updateStateById(id,(byte) 1);

        return AppResult.success();
    }

    /**
     * 回复站内信
     */
    @PostMapping("/reply")
    public AppResult reply(@Validated @RequestBody MessageReplyRequest request) {
        // 检验当前用户的状态
        Long userId = JWTUtil.getUserIdFromToken(Constants.JWT);
        UserInfoResponse userInfo = userService.selectById(userId);
        if (userInfo.getState().equals(Constants.IS_STATUS_STATE)) {
            // 返回用户状态异常
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        // 检验当前的站内信的状态
        Message existsMessage = messageService.selectById(request.getRepliedId());
        if (existsMessage == null
                || existsMessage.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        // 检验不能是自己回复自己
        if (userId == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.fail("不能回复自己的站内信");
        }

        // 构造返回对象
        Message message = new Message(); // 回复的信息
        message.setPostUserId(userId); //发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(request.getContent());

        // 调用Service层
        messageService.reply(request.getRepliedId(), message);

        return AppResult.success();
    }
}
